<template>
  <div class="center">
    <!-- 头部 -->
    <div class="table_header flex flex_bet flex-wrap">
      <div class="table_button flex felx_align">
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="Refresh"></el-button>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="btnaddBrand">添加</el-button>
        <div class="guidetext" @click="imgShow = true"><i class="iconfont iconiconfontwenhao1 guide"></i>操作指引</div>
      </div>
      <div class="table_searchs flex felx_align">
        <div class="table_search flex">
          <el-input placeholder="搜索" v-model="searchTable" class="input-with-select" size="small">
            <el-select v-model="select" slot="prepend" placeholder="请选择" class="table_select" style="width:105px">
              <!-- <el-option label="包名" value="package"></el-option> -->
              <el-option label="批次" value="batch"></el-option>
              <el-option label="归属" value="username"></el-option>
              <!-- <el-option label="网址" value="address"></el-option> -->
              <el-option label="应用名" value="app_name"></el-option>
            </el-select>
            <el-button slot="append" icon="el-icon-search" @click="idnameSearch"></el-button>
          </el-input>
        </div>
        <dynamicTable :checkboxVal="checkboxVal" @alter="alterCheckbok" />
      </div>
    </div>
    <!-- 设备归属管理table -->
    <el-table stripe style="width: 100%" :data="tableData" :key="key" border fit highlight-current-row ref="tableDataRef" max-height="535">
      <el-table-column v-if="colData[0].istrue" min-width="100" align="center" prop="username" label="归属"></el-table-column>
      <el-table-column v-if="colData[1].istrue" min-width="80" align="center" prop="batch" label="批次"></el-table-column>
      <el-table-column v-if="colData[2].istrue" min-width="130" align="center" prop="app_name" label="应用名称"></el-table-column>
      <el-table-column v-if="colData[3].istrue" min-width="160" align="center" prop="package" label="包名"></el-table-column>
      <el-table-column v-if="colData[4].istrue" min-width="60" align="center" prop="type" label="类型">
        <template slot-scope="scope">{{scope.row.type ? '白名单' : '黑名单'}}</template>
      </el-table-column>
      <el-table-column v-if="colData[5].istrue" min-width="160" align="center" prop="address" label="域名/地址"></el-table-column>
      <el-table-column v-if="colData[6].istrue" min-width="140" align="center" prop="create_time" label="更新时间">
        <template slot-scope="scope">{{scope.row.create_time| newDate}}</template>
      </el-table-column>
      <el-table-column min-width="150" align="center" prop="log" label="操作">
        <template slot-scope="scope">
          <el-row>
            <el-button size="mini" type="primary" @click="getqueryIdAppGround(scope.row.id)">编辑</el-button>
            <el-button size="mini" @click="deleteShow(scope.row.id)">删除</el-button>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="paging">
      <el-pagination :current-page.sync="listQuery.startSize" background @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[10, 50, 100, 200]"
        layout="total, sizes, prev, pager, next, jumper" :total="total" :page-size="listQuery.pageSize"></el-pagination>
    </div>
    <!-- 添加dialog表单 -->
      <el-dialog :title="editSubjects ? '应用内部网页跳转管控' : '编辑'" :visible.sync="dialogFormVisible" @close="addFormclose" :close-on-click-modal="false" :close-on-press-escape="false" width="40%">
        <el-form :model="addForm" ref="ruleForm" :rules="rules" class="diolog_adapt">
          <el-form-item label="批次:" label-width="100px" prop="batch">
            <el-select v-model="addForm.batch" placeholder="没有选中任何项" class="add_select" :disabled="!editSubjects" @change="batchChange" filterable>
              <el-option v-for="item in lotoptions" :key="item.id" :label="item.batch" :value="item.id.toString()"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="设置包名" label-width="100px" prop="package">
            <el-select v-model="addForm.package" placeholder="请选择包名" class="add_select" :disabled="packagetDisabled">
              <el-option v-for="item in AppPackage" :key="item.id" :label="`${item.app_package} (${item.app_name})`" :value="item.app_package"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="域名/地址:" label-width="100px" v-for="(domain,index) in addForm.address" :key="domain.key" :rules="{ required: true, message: '请输入域名/地址', trigger: 'blur' }"
            :prop="'address.' + index + '.value'">
            <div class="addPut">
              <el-input v-model="domain.value" placeholder="请输入网址"></el-input>
              <el-button v-if="index != 0" class="dlePut btnLocation" round size="mini" icon="el-icon-delete" @click.prevent="removeDomain(domain)"></el-button>
            </div>
          </el-form-item>
          <el-form-item label-width="100px">
            <el-button type="primary" size="mini" round @click="addDomain" icon="el-icon-upload">增加白名单网址</el-button>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false" size="mini" round>取 消</el-button>
          <el-button v-if="editSubjects" type="primary" @click="getaddAppGround('ruleForm')" size="mini" round>确 定</el-button>
          <el-button v-else type="primary" @click="geteditAppGround('ruleForm')" size="mini" round>编辑</el-button>
        </div>
      </el-dialog>
    <!-- 模板操作图片弹窗 -->
    <div class="component" v-if="imgShow">
      <div class="mbImg"><img src="@/assets/images/snDsf.png" alt=""></div>
      <div class="masking" @click="imgShow = false"></div>
    </div>
    <!-- 删除弹窗 -->
    <delete-Dialog title="" :visible.sync="deleteDialogs.show" width="25%" top="40vh" @deleteEvents="deleteEvents" :deleteText="deleteDialogs.deleteText" />
  </div>
</template>

<script>
import dynamicTable from "@/components/DynamicTable";
import { queryAppGroundAll, queryIdAppGround, AppPackage, addAppGround, editAppGround, deleteAppGround } from "@/api/deployment.js";
import deleteDialog from "@/components/deleteDialog";
import { getBatchTwo } from "@/api/equipment.js";
import tableMini from '@/utils/tableMini.js';
export default {
  mixins: [tableMini],
  components: { dynamicTable, deleteDialog },
  data() {
    return {
      checkboxVal: ["归属", "批次", "应用名称", "包名", '类型', "域名/地址", "更新时间"],
      select: "batch", //搜索条件
      //添加按钮控制
      dialogFormVisible: false,
      //编辑按钮控制
      editSubjects: true,
      //浏览器专题id
      subjectId: 0,
      //批次下拉选择
      lotoptions: [],
      //app包名
      AppPackage: [],
      tableData: [],
      packagetDisabled: true,
      //添加表单
      addForm: { batch: "", package: "", address: [{ value: '', key: Date.now() }], },
      rules: {
        batch: [{ required: true, message: "请输入批次", trigger: "blur" }],
        package: [{ required: true, message: "请输入包名", trigger: "blur" }]
      },
      listQuery: { startSize: 1, pageSize: 10, userId: localStorage.getItem("ID"), package: undefined, batch: undefined, username: undefined, address: undefined, app_name: undefined, sort: '' },
      imgShow: false
    }
  },
  created() {
    this.getTabularData()
    this.getBatchTwos()
  },
  methods: {
    //删除按钮事件
    deleteEvents() {
      let params = {
        userId: localStorage.getItem("ID"),
        last_ip: sessionStorage.getItem("Ip"),
        id: this.deleteDialogs.deleteId
      }
      deleteAppGround(params).then(res => {
        this.$message.success(res.msg)
        this.getTabularData()
      }).catch(err => {
        this.getTabularData()
      })
    },
    //批次change事件
    batchChange(val) {
      this.getAppPackage(val)
      this.packagetDisabled = false
    },
    //添加应用按钮事件
    getaddAppGround(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let addForm = JSON.parse(JSON.stringify(this.addForm))
          addForm.last_ip = sessionStorage.getItem("Ip")
          addForm.userId = localStorage.getItem("ID")
          addForm.address = this.addForm.address.map(item => item.value).toString()
          addForm.batch = this.addForm.batch
          addAppGround(addForm).then(res => {
            this.$message.success(res.msg)
            this.getTabularData()
            this.dialogFormVisible = false
          }).catch(err => { })
        } else {
          return false
        }
      })
    },
    //编辑应用按钮事件
    geteditAppGround(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let addForm = JSON.parse(JSON.stringify(this.addForm))
          addForm.last_ip = sessionStorage.getItem("Ip")
          addForm.userId = localStorage.getItem("ID")
          addForm.id = this.subjectId
          addForm.address = this.addForm.address.map(item => item.value).toString()
          editAppGround(addForm).then(res => {
            this.dialogFormVisible = false
            this.$message.success(res.msg)
            this.getTabularData()
          }).catch(err => { })
        } else {
          return false
        }
      })
    },
    //根据ID获取第三方应用
    getqueryIdAppGround(id) {
      this.packagetDisabled = true
      this.editSubjects = false
      this.subjectId = id
      queryIdAppGround({ id: id }).then(({ data }) => {
        this.dialogFormVisible = true
        this.addForm.batch = data.batch
        this.addForm.package = data.package
        data.address != null ? this.addForm.address = data.address.split(',').map(item => { return { 'value': item } }) : ''
        // this.addForm.type = data.type
      })
    },
    getTabularData() {
      queryAppGroundAll(this.listQuery).then(res => {
        this.tableData = res.data
        this.total = res.total
      }).catch(err => {
        this.tableData = []
        this.total = 0
      })
    },
    btnaddBrand() {
      this.packagetDisabled = true
      this.editSubjects = true
      this.dialogFormVisible = true
    },
    //根据ID获取包名信息
    getAppPackage(bId) {
      let data = { userId: localStorage.getItem("ID"), bId: bId }
      AppPackage(data).then(res => {
        this.AppPackage = res.data
      }).catch(err => {
        this.AppPackage = []
      })
    },
    //表单动态添加input
    removeDomain(item) {
      var index = this.addForm.address.indexOf(item)
      if (index !== -1) {
        this.addForm.address.splice(index, 1)
      }
    },
    addDomain() {
      if (this.addForm.address == 50) return this.$message({ type: 'warning', message: '限制50条数' })
      this.addForm.address.push({ value: '', key: Date.now() });
    },
    //根据ID获取批次列表
    getBatchTwos() {
      let data = { userId: localStorage.getItem("ID") }
      getBatchTwo(data).then(res => {
        this.lotoptions = res.data
      }).catch(err => {
        this.lotoptions = []
      })
    },
    //编辑添加表单关闭事件
    addFormclose() {
      this.$nextTick(() => {
        this.$refs.ruleForm.resetFields();
        this.addForm = this.$options.data().addForm
      })
    }
  }
}
</script>

<style scoped>
/deep/ .el-dialog__header {
  transform-origin: 50% 100%;
  border-bottom: 0.5px solid #e9e9e9;
}
</style>
